//
//  AddCircleViewController.m
//  安好
//
//  Created by rlp on 14-11-26.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "AddCircleViewController.h"

@interface AddCircleViewController ()
{
    
    UIView *view;
}
@end

@implementation AddCircleViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.attentionDict.count==0) {
        self.navigationItem.rightBarButtonItem=nil;
    }else{
        UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
        [rightButton setImage:[UIImage imageNamed:@"公用_完成"] forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    }
    
}

-(IBAction)loadheaderView:(id)sender{
    UIButton *btn = (UIButton *)sender;
    
    /**
     *  删除
     */
    [self.attentionDict removeObjectForKey:[self.attentions objectAtIndex:btn.tag-1]];
    [self.attentions removeObjectAtIndex:btn.tag-1];
    
    
    NSArray *views = self.buttonViewS.subviews;

    for (UIView *v in views)
    {
        [v removeFromSuperview];

    }
    
    
    [view removeFromSuperview];
    [self calculationsButtonView:nil];
    if (self.attentions.count==0) {
        [UIView animateWithDuration:0.6 animations:^
         {
             self.circleView.tableHeaderView = nil;

         } completion:^(BOOL finished)
         {
         }];
    }
}
/**
 *  计算所选择二级圈子的button
 *
 *  @param sender <#sender description#>
 */
-(IBAction)calculationsButtonView:(id)sender{

    
    NSInteger j = 0;
    for (int i=0; i<self.attentions.count; i++) {
        
        
        /**
         里面的button
         */
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        [button setTitle:[self.attentions objectAtIndex:i] forState:UIControlStateNormal];
        button.titleLabel.font=[UIFont systemFontOfSize:BUTTON_TEXTLABEL_FOUNT_SIZE];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 3;
//        button.layer.borderWidth = 1.0;
        button.layer.backgroundColor =TITLE_ARTICLE_CONTENTFONT_COLOR.CGColor;
        [button sizeToFit];
        button.frame = CGRectMake(0, 0, button.frame.size.width+10,  button.frame.size.height);
        button.tag = i+1;
        
        [button addTarget:self action:@selector(loadheaderView:) forControlEvents:UIControlEventTouchUpInside];
        
        /**
         获取buttonview
         */
        UIView *getButtonView=[[UIView alloc]initWithFrame:CGRectZero];
        CGFloat gap = 0;
        
        if (i>0) {
            getButtonView = [self.buttonViewS viewWithTag:i];
            gap=5;
        }
        
        
        
        UIView *viewButton =[[UIView alloc]initWithFrame:CGRectMake((getButtonView.frame.size.width+getButtonView.frame.origin.x+gap), (getButtonView.frame.size.height+5)*j,button.frame.size.width+20, button.frame.size.height)];
        viewButton.backgroundColor = [UIColor clearColor];
        viewButton.tag = i+1;//tag用的从1开始
        viewButton.layer.masksToBounds = YES;
        viewButton.layer.cornerRadius = 3;
        viewButton.layer.backgroundColor =TITLE_ARTICLE_CONTENTFONT_COLOR.CGColor;
        
        CGFloat sumW= viewButton.frame.size.width+viewButton.frame.origin.x;//计算viewButton是否有超界
        
        if (sumW>=self.buttonViewS.frame.size.width) {
            j++;

                 viewButton.frame =CGRectMake((getButtonView.frame.size.width+getButtonView.frame.origin.x+5)*0, (getButtonView.frame.size.height+5)*j,button.frame.size.width+20, button.frame.size.height);

        }
        
        
        
        
        [viewButton addSubview:button];
        [self.buttonViewS addSubview:viewButton];
        
        
        
        
        UIButton *buttonDel = [[UIButton alloc]initWithFrame:CGRectMake(viewButton.frame.size.width-20,(viewButton.frame.size.height-15)/2, 15, 15)];
        buttonDel.tag = i+1;

        [buttonDel setBackgroundImage:[UIImage imageNamed:@"圈子_退出"] forState:UIControlStateNormal];
        [buttonDel addTarget:self action:@selector(loadheaderView:) forControlEvents:UIControlEventTouchUpInside];

        [viewButton addSubview:buttonDel];
        
        
        self.buttonViewS.frame =CGRectMake(self.buttonViewS.frame.origin.x, self.buttonViewS.frame.origin.y, self.buttonViewS.frame.size.width, viewButton.frame.size.height+viewButton.frame.origin.y);
    }
    [view addSubview:self.buttonViewS];
    
    
    view.frame = CGRectMake(0, 0, kScreenWidth, self.buttonViewS.frame.origin.y+self.buttonViewS.frame.size.height+10);
    
    
    
    
    
    self.circleView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    
    
    
    UIView *headerBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, view.frame.size.height+10)];
    headerBackView.backgroundColor = [UIColor clearColor];
    
    
    [UIView animateWithDuration:0.6 animations:^
     {
         [headerBackView addSubview:view];
         
         self.circleView.tableHeaderView = headerBackView;
     } completion:^(BOOL finished)
     {
     }];

    

}

-(void)loadheaderView{
    
   
    view = [[UIView alloc]init];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 12,kScreenWidth-15*2 , 20) text:@"已添加的圈子" font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT] textColor:[ClassMethodsViewController colorWithHexString:BUTTON_TEXTLABEL_FOUNT_COLOR] backgroundColor:[UIColor clearColor] numberOfLines:1 lineSpacing:0];
    [view addSubview:label];
    
//    UIView *viewLine = [[UIView alloc]initWithFrame:CGRectMake(0, 43, kScreenWidth, 0.4)];
//    viewLine.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
//    
//    
//    [view addSubview:viewLine];
    
    
//    self.attentions = [[NSMutableArray alloc]initWithObjects:@"颈椎病",@"颈",@"颈椎病颈椎病",@"颈椎病",@"颈椎病",@"颈",@"颈椎病颈椎病",@"颈椎病",@"颈椎病",@"颈椎病",@"颈椎病",@"颈椎病", nil];
    self.buttonViewS = [[UIView alloc]initWithFrame:CGRectMake(15, 20+label.frame.origin.y, kScreenWidth-15*2, 0)];
    
    [self calculationsButtonView:nil];
    
    [view addSubview:self.buttonViewS];
    
    
    view.frame = CGRectMake(0, 0, kScreenWidth, self.buttonViewS.frame.origin.y+self.buttonViewS.frame.size.height+10);
    
    
    
    
    
    self.circleView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    
    
    
    UIView *headerBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, view.frame.size.height+10)];
    headerBackView.backgroundColor = [UIColor clearColor];
    [headerBackView addSubview:view];
    
    self.circleView.tableHeaderView = headerBackView;
    if (self.attentions.count==0) {
        self.circleView.tableHeaderView =nil;
    }

}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[AFHTTPRequestOperationManager manager].operationQueue cancelAllOperations];
    [self hiddenActionView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout=UIRectEdgeNone;
    [self makeNavBarView];
    self.circleArray = [[NSMutableArray alloc]initWithCapacity:10];
    if (!self.attentions) {
        self.attentions = [[NSMutableArray alloc]initWithCapacity:10];
    }
    if (!self.attentionDict) {
        self.attentionDict = [[NSMutableDictionary alloc]initWithCapacity:10];
    }else{
    
        [self.attentions removeAllObjects];
        [self.attentions addObjectsFromArray:[self.attentionDict allKeys]];
    
    
    }
    
    
    
    
    
    [self loadCircleData];
    self.circleView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin) style:UITableViewStylePlain];
    self.circleView.delegate = self;
    self.circleView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.circleView.showsHorizontalScrollIndicator = NO;
    self.circleView.showsVerticalScrollIndicator = NO;
    [self.circleView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉系统的分割线
    [self.view addSubview:self.circleView];
    [self loadheaderView];//初始化headerview



}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
 *  为关注圈子的数据加载
 */
-(void)loadCircleData{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:@"1" forKey:@"page"];
    [dict setObject:@"0" forKey:@"pid"];
    [dict setObject:@"20" forKey:@"pagesize"];
    
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_LIST] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
        }else{
            [self.circleArray removeAllObjects];
            for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
                CircleModelData *circlemodelData = [CircleModelData modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
                [self.circleArray addObject:circlemodelData];
            }
            [self.circleView reloadData];
            
        }
        
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];
    
}

#pragma mark - 设置导航条
-(void)makeNavBarView
{
    self.navigationItem.title = @"添加圈子";
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
//    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
//    [rightButton setImage:[UIImage imageNamed:@"公用_更多@2x.png"] forState:UIControlStateNormal];
//    [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
//    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}
#pragma mark -
#pragma mark -- click
-(void)leftButtonClicked:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger number=0;

        number = 1;
        
    return number;
}
-(IBAction)rightButtonClick:(id)sender{
    
     if (self.attentionDict.count==0) {
         UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"你现在没有关注的圈子,确定后将把之前关注的圈子取消关注" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"放弃",nil];
         [alertView show];
     }else{
         [self attentionCircle];
     }
    
  

}
/**
 *  关注圈子
 */
-(void)attentionCircle{
    
    NSMutableString *gids = [[NSMutableString alloc]initWithCapacity:10];
    
    for (int i=0; i<[self.attentionDict allValues].count; i++) {
        if ([self.attentionDict allValues].count==1) {
            [gids appendString:[[self.attentionDict allValues] objectAtIndex:0]];
            
        }else{
            if (i==0) {
                [gids appendString:[[self.attentionDict allValues] objectAtIndex:i]];
                [gids appendString:@","];
                
                
            }else if(i==[self.attentionDict allKeys].count-1){
                [gids appendString:[[self.attentionDict allValues] objectAtIndex:i]];
            }else{
                [gids appendString:[[self.attentionDict allValues] objectAtIndex:i]];
                [gids appendString:@","];
            }
        }
    }

    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:gids forKey:@"gids"];
    
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_BATCHUPDATE] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
        }else{
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger number=0;
    
        number = self.circleArray.count;
    return number;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger hight=44;
  
        hight = CIRCLETABLEVIEWCELL_HIGHT;
        
    return hight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
    static NSString *ID=@"tableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
        if (cell == nil) {
            if (kScreenWidth == 414) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"CircleTableViewCell" owner:self options:nil] lastObject];

            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"CircleTableViewCell" owner:self options:nil] firstObject];

            }
            /**
             *  线条的处理
             */
            
            /**
             *  线条的处理
             */
            
            UIView *bottomLineView = [[UIView alloc]init];
            
            if (indexPath.row != self.circleArray.count - 1)
            {
                bottomLineView.frame = CGRectMake(70, cell.contentView.height-0.5,kScreenWidth-70 - 5, 0.5);
            }
            else
            {
                bottomLineView.frame = CGRectMake(0, cell.contentView.height-0.5, kScreenWidth, 0.5);
            }
            
            bottomLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
            [cell.contentView addSubview:bottomLineView];

        }
        [[(CircleTableViewCell *)cell icon] setImageURLStr:[NSString stringWithFormat:@"%@",[[self.circleArray objectAtIndex:indexPath.row] icon]] placeholder:nil];
        
        [(CircleTableViewCell *)cell title].text = [[self.circleArray objectAtIndex:indexPath.row] title];
        [(CircleTableViewCell *)cell subtitle].text =[[self.circleArray objectAtIndex:indexPath.row] lastposttitle];
        
        [[(CircleTableViewCell *)cell thread] setTitle:[NSString stringWithFormat:@" %@",[[self.circleArray objectAtIndex:indexPath.row] threads]] forState:UIControlStateNormal];
        [[(CircleTableViewCell *)cell post] setTitle:[NSString stringWithFormat:@" %@",[[self.circleArray objectAtIndex:indexPath.row] posts]] forState:UIControlStateNormal];
    [(CircleTableViewCell *)cell pushImage].hidden = NO;

    
    
        
        
        

    // Configure the cell...
    
      cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AddCircleSecondViewController *cslVC = [[AddCircleSecondViewController alloc] initWithNibName:@"AddCircleSecondViewController" bundle:nil];
    cslVC.circleModelData = [self.circleArray objectAtIndex:indexPath.row];
    cslVC.circleModelDatas =self.circleArray;
    cslVC.attentionDict =self.attentionDict;
    cslVC.delegate = self;
    [self.navigationController pushViewController:cslVC animated:YES];
    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark -- UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            [self attentionCircle];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark -
#pragma mark -- AddCircleSecondLevelDelegate
/*
-(void)selectedWithAttentions:(NSMutableArray *)attentions{
    
    
    
    
    
    for (int i=0; i<attentions.count; i++) {
        
        [self.attentionDict setObject:[[attentions objectAtIndex:i] gid] forKey:[[attentions objectAtIndex:i] title]];
        MyNSLog("self.attentionDict ==%@",self.attentionDict );
//        [self.attentions addObject:[[attentions objectAtIndex:i] title]];
    }
    [self.attentions removeAllObjects];
    [self.attentions addObjectsFromArray:[self.attentionDict allKeys]];
    NSArray *views = self.buttonViewS.subviews;
    
    for (UIView *v in views)
    {
        [v removeFromSuperview];
        
    }
    [view removeFromSuperview];
    [self calculationsButtonView:nil];
    if (self.attentions.count==0) {
        [UIView animateWithDuration:0.6 animations:^
         {
             self.circleView.tableHeaderView = nil;
             
         } completion:^(BOOL finished)
         {
         }];
    }

}
 */
-(void)selectedWithAttentions:(NSMutableArray *)attentions delAttentions:(NSMutableArray *)delAttentions{
    
    if (!attentions) {
        attentions = [[NSMutableArray alloc]init];
    }
    if (!delAttentions) {
        delAttentions = [[NSMutableArray alloc]init];
    }
    for (int i=0; i<attentions.count; i++) {
        
        [self.attentionDict setObject:[[attentions objectAtIndex:i] gid] forKey:[[attentions objectAtIndex:i] title]];
        MyNSLog("self.attentionDict ==%@",self.attentionDict );
        //        [self.attentions addObject:[[attentions objectAtIndex:i] title]];
    }
    for (int i=0; i<delAttentions.count; i++) {
        
        [self.attentionDict removeObjectForKey:[[delAttentions objectAtIndex:i] title]];
        MyNSLog("self.attentionDict ==%@",self.attentionDict );
        //        [self.attentions addObject:[[attentions objectAtIndex:i] title]];
    }
    
    
    [self.attentions removeAllObjects];
    [self.attentions addObjectsFromArray:[self.attentionDict allKeys]];
    NSArray *views = self.buttonViewS.subviews;
    
    for (UIView *v in views)
    {
        [v removeFromSuperview];
        
    }
    [view removeFromSuperview];
    [self calculationsButtonView:nil];
    if (self.attentions.count==0) {
        [UIView animateWithDuration:0.6 animations:^
         {
             self.circleView.tableHeaderView = nil;
             
         } completion:^(BOOL finished)
         {
         }];
    }

}

@end
